import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/core/model/account_mine.dart';
import 'package:flutter_bilibili/core/shared_preferences/shared_preference_util.dart';
import 'package:flutter_bilibili/ui/pages/home/comic/home_comic.dart';
import 'package:flutter_bilibili/ui/pages/home/recommend/home_recommend.dart';
import 'package:flutter_bilibili/ui/pages/home/search/search.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_bilibili/core/I18n/str_res_keys.dart';
import 'package:get/get.dart';
import '../../../core/I18n/str_res_keys.dart';
import '../../../core/event_bus/event_bus.dart';
import '../../../core/service/request/login_request.dart';
import '../../../core/service/utils/constant.dart';
import '../../../core/shared_preferences/bilibili_shared_preference.dart';
import '../../shared/params_sign.dart';
import '../../widgets/bilibili_scroll.dart';
import '../../widgets/rectangle_checkBox.dart';
import '../live/live.dart';
import '../login/login.dart';

class HYHomeContent extends StatefulWidget {
  const HYHomeContent({Key? key}) : super(key: key);

  @override
  State<HYHomeContent> createState() => _HYHomeContentState();
}

class _HYHomeContentState extends State<HYHomeContent> {
  /// 极光认证
  /// 统一 key - f_result_key
  /// 错误码 - f_code_key
  /// 回调的提示信息，统一返回 flutter 为 message - f_msg_key
  /// 运营商信息 - f_opr_key
  final String f_result_key = "result";
  final String f_code_key = "code";
  final String f_msg_key = "message";
  final String f_opr_key = "operator";

  // late TextEditingController _controllerPHone;

  // late Jverify jverify;
  // String? _token;

  late ScrollController _scrollController;
  late bool _tempUserAgreement;
  late bool _tempTeenagerMode;

  ///是否登录
  late bool isLogin;

  ///用户头像
  String _userFace = "";

  @override
  void initState() {
    // if (Platform.isAndroid) {
    //   Jverify jverify = Jverify();
    //
    //   ///极光认证初始化
    //   initPlatformState();
    //
    //   ///极光认证sdk初始化
    //   isInitSuccess();
    //
    //   ///获取号码认证 Token
    //   getToken();
    //
    //   ///预取号
    //   preLogin();
    // }

    ///查找是否同意了用户协议
    initUserAgreement();

    ///查找青少年模式
    initTeenagerMode();

    ///获取登录状态，获取用户基本信息和我的界面基本信息
    iniAccountMine();

    ///登录完成后传来头像的数据，在此接收
    accountMineEventBus.on<HYAccountMineModel>().listen((event) {
      if (mounted) {
        setState(() {
          _userFace = event.data.face;
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ///DefaultTabController用于tabbar和tabbarView
    return DefaultTabController(
      ///设置几个tabBarItem
      length: 7,
      initialIndex: 1,

      ///上划
      child: NestedScrollView(
        headerSliverBuilder: (ctx, innerBoxIsScrolled) {
          return [
            SliverAppBar(
              toolbarHeight: 0.08.sh,

              leading: null,

              ///搜索和用户头像
              title: buildHomeUserIconAndSearch(),

              ///右侧工具栏
              actions: buildHomeActions(),

              ///向上滑动无需停留顶部
              pinned: false,

              floating: false,
              snap: false,
              backgroundColor: Colors.white,
            ),
            SliverAppBar(
              ///设置高度
              toolbarHeight: 0.07.sh,

              ///tabBar
              title: buildHomeTabBar(),

              ///向上滑动需停留顶部
              pinned: true,

              floating: true,
              snap: true,
              backgroundColor: Colors.white,
            ),
          ];
        },

        ///tabBarView
        body: buildHomeTabBarView(),
      ),
    );
  }

  // Future<void> initPlatformState() async {
  //   // 初始化 SDK 之前添加监听
  //   jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
  //     print("receive sdk setup call back event :${event.toMap()}");
  //   });
  //
  //   jverify.setDebugMode(true); // 打开调试模式
  //   jverify.setup(
  //       appKey: "4fedb3342b7faeab82225790", //"你自己应用的 AppKey",
  //       channel: "devloper-default"); // 初始化sdk,  appKey 和 channel 只对ios设置有效
  //   if (!mounted) return;
  //
  //   /// 授权页面点击时间监听
  //   jverify.addAuthPageEventListener((JVAuthPageEvent event) {
  //     print("receive auth page event :${event.toMap()}");
  //   });
  // }
  //
  // void isInitSuccess() {
  //   jverify.isInitSuccess().then((map) {
  //     bool result = map[f_result_key];
  //     setState(() {
  //       if (result) {
  //         _result = "sdk 初始换成功";
  //       } else {
  //         _result = "sdk 初始换失败";
  //       }
  //     });
  //   });
  // }
  //
  // /// 判断当前网络环境是否可以发起认证
  // void checkVerifyEnable() {
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     setState(() {
  //       if (result) {
  //         _result = "当前网络环境【支持认证】！";
  //       } else {
  //         _result = "当前网络环境【不支持认证】！";
  //       }
  //     });
  //   });
  // }
  //
  // /// 获取号码认证token
  // void getToken() {
  //   setState(() {
  //     _showLoading(context);
  //   });
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     if (result) {
  //       jverify.getToken().then((map) {
  //         int code = map[f_code_key];
  //         _token = map[f_msg_key];
  //         String operator = map[f_opr_key];
  //         setState(() {
  //           _hideLoading();
  //           _result = "[$code] message = $_token, operator = $operator";
  //         });
  //       });
  //     } else {
  //       setState(() {
  //         _hideLoading();
  //         _result = "[2016],msg = 当前网络环境不支持认证";
  //       });
  //     }
  //   });
  // }
  //
  // ///预取号
  // void preLogin() {
  //   setState(() {
  //     _showLoading(context);
  //   });
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     if (result) {
  //       jverify.preLogin().then((map) {
  //         print("预取号接口回调：${map.toString()}");
  //         int code = map[f_code_key];
  //         String message = map[f_msg_key];
  //         setState(() {
  //           _hideLoading();
  //           _result = "[$code] message = $message";
  //         });
  //       });
  //     } else {
  //       setState(() {
  //         _hideLoading();
  //         _result = "[2016],msg = 当前网络环境不支持认证";
  //       });
  //     }
  //   });
  // }

  // /// SDK 请求授权一键登录（弹出版本）
  // void loginAuth() {
  //   setState(() {
  //     _showLoading(context);
  //   });
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     if (result) {
  //       final screenSize = MediaQuery.of(context).size;
  //       final screenWidth = screenSize.width;
  //       final screenHeight = screenSize.height;
  //       bool isiOS = Platform.isIOS;
  //
  //       JVUIConfig uiConfig = JVUIConfig();
  //       uiConfig.logoHidden = true;
  //       uiConfig.numberColor = HYAppTheme.norTextColors.value;
  //       uiConfig.numberTextBold = true;
  //       uiConfig.numberSize = HYAppTheme.normalFontSize.toInt();
  //       uiConfig.numFieldOffsetY = 70;
  //       uiConfig.sloganHidden = true;
  //       uiConfig.logBtnOffsetY = 110;
  //       uiConfig.logBtnWidth = (screenWidth - 180).toInt();
  //       uiConfig.needStartAnim = true;
  //       uiConfig.needCloseAnim = true;
  //       uiConfig.privacyCheckboxSize = 13;
  //       uiConfig.privacyTextSize = 10;
  //       uiConfig.privacyOffsetX = 10;
  //       uiConfig.privacyTopOffsetY = 190;
  //       uiConfig.privacyItem = [
  //         JVPrivacy("用户协议、隐私政策", "http://www.baidu.com", separator: "、"),
  //         JVPrivacy("中国移动号码认证系统服务协议", "http://www.baidu.com", separator: "、"),
  //       ];
  //       uiConfig.privacyUnderlineText = false;
  //
  //       //弹框模式
  //       JVPopViewConfig popViewConfig = JVPopViewConfig();
  //       popViewConfig.width = (screenWidth - 140).toInt();
  //       popViewConfig.height = (screenHeight - 450).toInt();
  //
  //       uiConfig.popViewConfig = popViewConfig;
  //
  //       /// 添加自定义的 控件 到授权界面
  //       List<JVCustomWidget> widgetList = [];
  //
  //       const jVerifyHeaderText = "jv_header_text"; // 标识控件 id
  //       JVCustomWidget jVerifyHeaderTextWidget =
  //           JVCustomWidget(jVerifyHeaderText, JVCustomWidgetType.textView);
  //       jVerifyHeaderTextWidget.title = "登录注册解锁更多内容";
  //       jVerifyHeaderTextWidget.top = 25;
  //       jVerifyHeaderTextWidget.width = screenWidth.toInt();
  //       jVerifyHeaderTextWidget.backgroundColor = Colors.transparent.value;
  //       jVerifyHeaderTextWidget.isShowUnderline = true;
  //       jVerifyHeaderTextWidget.titleFont = HYAppTheme.xSmallFontSize;
  //       jVerifyHeaderTextWidget.textAlignment = JVTextAlignmentType.center;
  //       jVerifyHeaderTextWidget.isShowUnderline = false;
  //
  //       const jVerifyOtherLoginText = "jv_other_login_text"; // 标识控件 id
  //       JVCustomWidget jVerifyOtherLoginTextWidget =
  //           JVCustomWidget(jVerifyOtherLoginText, JVCustomWidgetType.textView);
  //       jVerifyOtherLoginTextWidget.title = "其他登录方式";
  //       jVerifyOtherLoginTextWidget.top = 160;
  //       jVerifyOtherLoginTextWidget.width = screenWidth.toInt();
  //       jVerifyOtherLoginTextWidget.backgroundColor = Colors.transparent.value;
  //       jVerifyOtherLoginTextWidget.titleColor =
  //           const Color.fromRGBO(77, 77, 77, 1).value;
  //       jVerifyOtherLoginTextWidget.isShowUnderline = false;
  //       jVerifyOtherLoginTextWidget.titleFont = HYAppTheme.xSmallFontSize;
  //       jVerifyOtherLoginTextWidget.textAlignment = JVTextAlignmentType.center;
  //
  //       jverify.addClikWidgetEventListener(jVerifyOtherLoginText, (eventId) {
  //         print("receive listener - click widget event :$eventId");
  //         if (jVerifyOtherLoginText == eventId) {
  //           print("receive listener - 点击【关闭按钮】");
  //
  //         }
  //       });
  //
  //       const String jVerifyCloseText = "jv_close_button"; // 标识控件 id
  //       JVCustomWidget jVerifyCloseTextWidget =
  //           JVCustomWidget(jVerifyCloseText, JVCustomWidgetType.button);
  //       jVerifyCloseTextWidget.title = "X";
  //       jVerifyCloseTextWidget.titleColor = HYAppTheme.norGrayColor.value;
  //       jVerifyCloseTextWidget.top = 0;
  //       jVerifyCloseTextWidget.width = screenWidth.toInt();
  //       jVerifyCloseTextWidget.isShowUnderline = false;
  //       jVerifyCloseTextWidget.textAlignment = JVTextAlignmentType.right;
  //       jVerifyCloseTextWidget.backgroundColor = Colors.transparent.value;
  //
  //       widgetList.add(jVerifyHeaderTextWidget);
  //       widgetList.add(jVerifyOtherLoginTextWidget);
  //       widgetList.add(jVerifyCloseTextWidget);
  //
  //       /// 步骤 1：调用接口设置 UI
  //       jverify.setCustomAuthorizationView(false, uiConfig,
  //           landscapeConfig: uiConfig, widgets: widgetList);
  //
  //       /// 步骤 2：调用一键登录接口
  //
  //       /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
  //       /// 先，添加 loginAuthSyncApi 接口回调的监听
  //       jverify.addLoginAuthCallBackListener((event) {
  //         setState(() {
  //           _hideLoading();
  //           _hideLoading();
  //           _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
  //         });
  //         print(
  //             "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");
  //       });
  //
  //       /// 再，执行同步的一键登录接口
  //       jverify.loginAuthSyncApi(autoDismiss: true);
  //     } else {
  //       setState(() {
  //         _hideLoading();
  //         _result = "[2016],msg = 当前网络环境不支持认证";
  //       });
  //       /*
  //       /// 方式二：使用异步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
  //       /// 先，执行异步的一键登录接口
  //       jverify.loginAuth(true).then((map) {
  //         /// 再，在回调里获取 loginAuth 接口异步返回数据（如果是通过添加 JVLoginAuthCallBackListener 监听来获取返回数据，则忽略此步骤）
  //         int code = map[f_code_key];
  //         String content = map[f_msg_key];
  //         String operator = map[f_opr_key];
  //         setState(() {
  //          _hideLoading();
  //           _result = "接口异步返回数据：[$code] message = $content";
  //         });
  //         print("通过接口异步返回，获取到 loginAuth 接口返回数据，code=$code,message = $content,operator = $operator");
  //       });
  //       */
  //     }
  //   });
  // }
  /// SDK 请求授权一键登录（界面版本）
  // void loginAuth() {
  //   setState(() {
  //     _showLoading(context);
  //   });
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     if (result) {
  //       final screenSize = MediaQuery.of(context).size;
  //       final screenWidth = screenSize.width;
  //       final screenHeight = screenSize.height;
  //       bool isiOS = Platform.isIOS;
  //
  //       JVUIConfig uiConfig = JVUIConfig();
  //       uiConfig.privacyCheckboxSize = 13;
  //       uiConfig.privacyTextSize = 10;
  //       uiConfig.privacyOffsetX = 50;
  //       uiConfig.privacyTopOffsetY = 350;
  //       uiConfig.privacyItem = [
  //         JVPrivacy("用户协议、隐私政策", "http://www.baidu.com", separator: "、"),
  //         JVPrivacy("中国移动号码认证系统服务协议", "http://www.baidu.com", separator: "、"),
  //       ];
  //       uiConfig.privacyUnderlineText = false;
  //
  //       List<JVCustomWidget> widgetList = [];
  //
  //       /// 步骤 1：调用接口设置 UI
  //       jverify.setCustomAuthorizationView(false, uiConfig,
  //           landscapeConfig: uiConfig, widgets: widgetList);
  //
  //       /// 步骤 2：调用一键登录接口
  //       /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
  //       /// 先，添加 loginAuthSyncApi 接口回调的监听
  //       jverify.addLoginAuthCallBackListener((event) {
  //         setState(() {
  //           _hideLoading();
  //           _hideLoading();
  //           _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
  //         });
  //         print(
  //             "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");
  //       });
  //
  //       /// 再，执行同步的一键登录接口
  //       jverify.loginAuthSyncApi(autoDismiss: true);
  //     } else {
  //       setState(() {
  //         _hideLoading();
  //         _result = "[2016],msg = 当前网络环境不支持认证";
  //       });
  //     }
  //   });
  // }

  // void _showLoading(BuildContext context) {
  //   // LoadingDialog.show(context);
  // }
  //
  // void _hideLoading() {
  //   // LoadingDialog.hidden();
  // }

  ///圆形图标（登录图标
  Widget buildHomeUserIcon(BuildContext context, String userInfo) {
    var _flag = true;
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 20).r,
      child: userInfo.isEmpty
          ? CircleAvatar(
              backgroundColor: Theme.of(context).canvasColor,
              radius: 20.r,
              child: TextButton(
                onPressed: () async {
                  SmartDialog.showLoading(
                    displayTime: const Duration(seconds: 2),
                    maskColor: const Color.fromRGBO(0, 0, 0, .4),
                    builder: (ctx) {
                      return Container(
                        decoration: BoxDecoration(
                            color: const Color.fromRGBO(0, 0, 0, .8),
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.w))),
                        height: 80.h,
                        width: 80.w,
                        padding: const EdgeInsets.all(5).r,
                        child: Column(
                          children: [
                            Image.asset(
                              ImageAssets.ploadingGif,
                              width: 35.w,
                              height: 35.h,
                            ),
                            10.verticalSpace,
                            Text(
                              SR.loading.tr,
                              style: TextStyle(
                                  color: HYAppTheme.norGrayColor,
                                  fontSize: HYAppTheme.xxSmallFontSize),
                            )
                          ],
                        ),
                      );
                    },
                  ).whenComplete(() {
                    SmartDialog.dismiss();
                    SmartDialog.show(
                      builder: (ctx) {
                        return Card(
                          child: Container(
                            padding: const EdgeInsets.all(10).r,
                            width: 270.w,
                            child: Stack(
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(15).r,
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        SR.login2UnlockMoreAmazingContent.tr,
                                        style: TextStyle(
                                            color: HYAppTheme.norTextColors,
                                            fontSize:
                                                HYAppTheme.xSmallFontSize),
                                        textAlign: TextAlign.center,
                                      ),
                                      Container(
                                        padding: const EdgeInsets.only(
                                                top: 30, bottom: 20)
                                            .r,
                                        child: Text(
                                          "183****1731",
                                          style: TextStyle(
                                              fontSize:
                                                  HYAppTheme.normalFontSize,
                                              color: HYAppTheme.norTextColors),
                                        ),
                                      ),
                                      TextButton(
                                        style: ButtonStyle(
                                            padding: MaterialStateProperty.all(
                                                const EdgeInsets.symmetric(
                                                        vertical: 10)
                                                    .r),
                                            backgroundColor:
                                                MaterialStateProperty.all(
                                                    HYAppTheme
                                                        .norMainThemeColors)),
                                        onPressed: () {
                                          ///一键登录
                                          // loginAuth();
                                        },
                                        child: Container(
                                          padding: const EdgeInsets.symmetric(
                                                  vertical: 4)
                                              .r,
                                          alignment:
                                              AlignmentDirectional.center,
                                          width: double.infinity,
                                          child: Text(
                                            SR.oneClickLogin.tr.toUpperCase(),
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize:
                                                    HYAppTheme.xSmallFontSize),
                                          ),
                                        ),
                                      ),
                                      Container(
                                        padding: const EdgeInsets.only(
                                                top: 15, bottom: 20)
                                            .r,
                                        child: GestureDetector(
                                          onTap: () {
                                            Navigator.of(context).pushNamed(
                                                HYLoginScreen.routeName);
                                            SmartDialog.dismiss();
                                          },
                                          child: Text(
                                            SR.otherWay.tr,
                                            style: TextStyle(
                                                fontSize:
                                                    HYAppTheme.xSmallFontSize,
                                                color:
                                                    HYAppTheme.norGray04Color),
                                            textAlign: TextAlign.center,
                                          ),
                                        ),
                                      ),
                                      Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            child: RectangleCheckBox(
                                              ///自定义矩形的checkbox
                                              size: 14.sp,
                                              checkedColor:
                                                  HYAppTheme.norMainThemeColors,
                                              isChecked: _flag,
                                              onTap: (value) {
                                                _flag = value!;
                                              },
                                            ),
                                            padding: const EdgeInsets.only(
                                                    right: 3, top: 3)
                                                .r,
                                          ),
                                          5.horizontalSpace,
                                          buildHomeAgreement(),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                                Positioned(
                                  right: 0,
                                  top: 0,
                                  child: Icon(
                                    Icons.close,
                                    color: HYAppTheme.norGrayColor,
                                    size: 13.sp,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    );
                  });
                  // await Future.delayed(const Duration(seconds: 2)).then(
                  //   (value) {
                  //     SmartDialog.dismiss();
                  //
                  //     //未登录情况下
                  //     // Navigator.of(context).pushNamed(HYLoginScreen.routeName);
                  //   },
                  // );
                },
                child: Text(
                  SR.login.tr,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: HYAppTheme.norMainThemeColors,
                    fontSize: HYAppTheme.xxxSmallFontSize,
                  ),
                ),
              ),
            )
          : GestureDetector(
              onTap: () {
                ///已经登陆的情况下：发一个index，更改底部导航栏的下标
                mineEventBus.fire(4);
              },
              child: CircleAvatar(
                backgroundImage: NetworkImage(userInfo),
              ),
            ),
    );
  }

  ///用户协议
  Widget buildHomeAgreement() {
    return Expanded(
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
              text: SR.userAgreementText01.tr,
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: SR.userAgreementText02.tr,
              style: TextStyle(
                  color: Colors.blue, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: SR.userAgreementText03.tr,
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: SR.userAgreementText04.tr,
              style: TextStyle(
                  color: Colors.blue, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: SR.userAgreementText05.tr,
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
          ],
        ),
      ),
    );
  }

  ///用户头像和搜索
  Widget buildHomeUserIconAndSearch() {
    return Row(
      children: [
        ///用户头像
        buildHomeUserIcon(context, _userFace),
        Expanded(
          child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, HYHomeSearchScreen.routeName);
            },
            child: Container(
              alignment: Alignment.centerLeft,
              child: Container(
                  padding: const EdgeInsets.only(left: 15, top: 8, bottom: 8).r,
                  child: Image.asset(ImageAssets.searchCustomPNG)),
              height: 35.h,
              decoration: BoxDecoration(
                  color: HYAppTheme.norWhite02Color,
                  borderRadius: BorderRadius.circular(20.r)),
            ),
          ),
        ),
      ],
    );
  }

  ///右侧工具栏
  List<Widget> buildHomeActions() {
    return [
      IconButton(
          onPressed: () => print("game"),
          icon: Image.asset(
            ImageAssets.gameCustomPNG,
            width: HYAppTheme.normalFontSize,
            height: HYAppTheme.normalFontSize,
          )),
      5.horizontalSpace,
      IconButton(
          onPressed: () => print("more"),
          icon: Image.asset(
            ImageAssets.mailCustomPNG,
            width: HYAppTheme.normalFontSize,
            height: HYAppTheme.normalFontSize,
          )),
      5.horizontalSpace,
    ];
  }

  ///直播、推荐那个几个item的tabbar
  TabBar buildHomeTabBar() {
    return TabBar(
      tabs: [
        Tab(text: SR.live.tr.toUpperCase()),
        Tab(text: SR.recommend.tr.toUpperCase()),
        Tab(text: SR.hot.tr.toUpperCase()),
        Tab(text: SR.comic.tr.toUpperCase()),
        Tab(text: SR.movie.tr.toUpperCase()),
        Tab(text: SR.covid.tr.toUpperCase()),
        Tab(text: SR.journey.tr.toUpperCase()),
      ],
      indicatorColor: HYAppTheme.norMainThemeColors,
      unselectedLabelColor: HYAppTheme.unselectedLabelColor,
      labelColor: HYAppTheme.norMainThemeColors,
      indicatorSize: TabBarIndicatorSize.label,
      labelStyle: const TextStyle(fontWeight: FontWeight.bold),
      unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),

      ///下划线的厚度
      indicatorWeight: 3.h,
      isScrollable: true,
    );
  }

  ///home中主要显示的内容，与tabBar对应
  Widget buildHomeTabBarView() {
    ///未同意用户协议
    return _tempUserAgreement == false
        ? Container()
        : TabBarView(
            children: buildTabBarViewChildren(),
          );
  }

  List<Widget> buildTabBarViewChildren() {
    List<Widget> _widgets = [];
    for (int i = 0; i < 7; i++) {
      Widget _child;
      if (i == 0) {
        ///直播
        _child = const HYLiveScreen();
      } else if (i == 1) {
        ///推荐
        _child = const HYHomeRecommendScreen();
      } else if (i == 2) {
        ///动画
        _child = const HYHomeComicScreen();
      } else {
        _child = Container();
      }
      _widgets.add(_child);
    }
    return _widgets;
  }

  ///弹出用户协议对话框
  void showUserAgreementDialog() {
    SmartDialog.show(
      clickMaskDismiss: false,
      builder: (context) {
        return Card(
          child: Container(
            width: 250.w,
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15).r,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  SR.userAgreementAndPrivacyPolicyTips.tr.toUpperCase(),
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.normal,
                      fontSize: HYAppTheme.xSmallFontSize),
                  textAlign: TextAlign.center,
                ),
                10.verticalSpace,
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(2.r)),
                    color: HYAppTheme.norGrayColor.withOpacity(.2),
                  ),
                  height: 130.h,
                  padding: EdgeInsets.zero,
                  child: BilibiliScroll(
                    scrollBar: buildBilibiliScrollBar(),
                    child: buildBilibiliScrollChild(),
                  ),
                ),
                8.verticalSpace,
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: SR.userAgreementDetailDescText01.tr,
                        style: TextStyle(
                          fontSize: HYAppTheme.xxxSmallFontSize,
                          color: HYAppTheme.norGrayColor,
                        ),
                      ),
                      TextSpan(
                        text: SR.userAgreementDetailDescText02.tr.toUpperCase(),
                        style: TextStyle(
                          fontSize: HYAppTheme.xxxSmallFontSize,
                          color: Colors.blue,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      TextSpan(
                        text: SR.userAgreementText03.tr,
                        style: TextStyle(
                          fontSize: HYAppTheme.xxxSmallFontSize,
                          color: HYAppTheme.norGrayColor,
                        ),
                      ),
                      TextSpan(
                        text: SR.userAgreementDetailDescText03.tr.toUpperCase(),
                        style: TextStyle(
                          fontSize: HYAppTheme.xxxSmallFontSize,
                          color: Colors.blue,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      TextSpan(
                        text: SR.userAgreementDetailDescText04.tr,
                        style: TextStyle(
                          fontSize: HYAppTheme.xxxSmallFontSize,
                          color: HYAppTheme.norGrayColor,
                        ),
                      ),
                    ],
                  ),
                ),
                5.verticalSpace,
                GestureDetector(
                  onTap: () {
                    ///退出APP(不同意协议就退出）
                    SystemNavigator.pop();
                  },
                  child: Text(
                    SR.disagree.tr,
                    style: TextStyle(
                      fontSize: HYAppTheme.xxSmallFontSize,
                      color: HYAppTheme.norGrayColor,
                    ),
                  ),
                ),
                8.verticalSpace,
                TextButton(
                  style: ButtonStyle(
                      padding: MaterialStateProperty.all(
                          const EdgeInsets.symmetric(vertical: 5).r),
                      backgroundColor: MaterialStateProperty.all(
                          HYAppTheme.norMainThemeColors)),
                  onPressed: () {
                    ///同意用户协议后，记录键值对
                    SmartDialog.dismiss();
                    SharedPreferenceUtil.setBool(
                        BilibiliSharedPreference.appUserAgreementPrivatePolicy,
                        true);

                    ///青少年模式弹框
                    _tempTeenagerMode = SharedPreferenceUtil.getBool(
                        BilibiliSharedPreference.teenagerMode)!;
                    if (_tempUserAgreement == false) {
                      Future.delayed(const Duration(seconds: 1), () {
                        showTeenagerModeDialog();
                      });
                    }
                    if (mounted) {
                      setState(() {});
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 4).r,
                    alignment: AlignmentDirectional.center,
                    width: double.infinity,
                    child: Text(
                      SR.agree.tr.toUpperCase(),
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: HYAppTheme.xSmallFontSize,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget buildBilibiliScrollBar() {
    return Container(
      margin: EdgeInsets.only(right: 2.r, top: 2.r, bottom: 2.r),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(2.r)),
        color: HYAppTheme.norMainThemeColors.withOpacity(.5),
      ),
      height: 30.r,
      width: 4.r,
    );
  }

  Widget buildBilibiliScrollChild() {
    return ListView(
      padding: EdgeInsets.zero,
      children: [
        Text(
          SR.userAgreementDetailDesc.tr,
          style: TextStyle(
            color: Colors.black,
            fontSize: HYAppTheme.xxSmallFontSize,
          ),
        ),
      ],
    );
  }

  ///青少年模式弹框
  void showTeenagerModeDialog() {
    SmartDialog.show(
      builder: (ctx) {
        return Card(
          shape: RoundedRectangleBorder(
              borderRadius: const BorderRadius.all(Radius.circular(8)).r),
          child: Container(
            width: 250.w,
            padding: const EdgeInsets.symmetric(vertical: 25, horizontal: 15).r,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  ImageAssets.teenagerModePNG,
                  width: 50.r,
                  height: 50.r,
                ),
                15.verticalSpace,
                Text(
                  SR.teenagerModeDetailDesc.tr,
                  style: TextStyle(
                    color: HYAppTheme.norGrayColor,
                    fontSize: HYAppTheme.xxSmallFontSize,
                  ),
                ),
                10.verticalSpace,
                Text(
                  SR.goIntoTeenMode.tr,
                  style: TextStyle(
                      color: HYAppTheme.norGrayColor,
                      fontSize: HYAppTheme.xxSmallFontSize,
                      fontWeight: FontWeight.bold),
                ),
                15.verticalSpace,
                GestureDetector(
                  onTap: () {
                    SmartDialog.dismiss();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(vertical: 5.r),
                    width: 220.w,
                    decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.all(const Radius.circular(5).r),
                        border: Border.all(
                            color: HYAppTheme.norGrayColor.withOpacity(.4))),
                    child: Text(
                      SR.iKnowIt.tr.toUpperCase(),
                      style: TextStyle(
                          fontSize: HYAppTheme.xxSmallFontSize,
                          color: Colors.black,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                )
              ],
            ),
          ),
        );
      },
      clickMaskDismiss: false,
    );
  }

  void initUserAgreement() {
    ///判断本地协议是否同意
    _tempUserAgreement = SharedPreferenceUtil.getBool(
        BilibiliSharedPreference.appUserAgreementPrivatePolicy)!;
    if (_tempUserAgreement == false) {
      Future.delayed(Duration(seconds: 1), () {
        showUserAgreementDialog();
      });
    }
  }

  void initTeenagerMode() {
    _tempTeenagerMode =
        SharedPreferenceUtil.getBool(BilibiliSharedPreference.teenagerMode)!;
    if (_tempTeenagerMode == false && _tempUserAgreement == true) {
      Future.delayed(const Duration(seconds: 1), () {
        showTeenagerModeDialog();
      });
    }
  }

  void iniAccountMine() {
    isLogin =
        SharedPreferenceUtil.getBool(BilibiliSharedPreference.isLogin) ?? false;

    ///获取我的界面的数据
    Map<String, dynamic> params = {
      'appkey': Constant.appKey,
      'build': '6720300',
      'mobi_app': 'android',
      'platform': 'android',
      'bili_link_new': '1',
      'c_locale': 'zh_CN',
      'channel': 'html5_search_baidu',
      'disable_rcmd': '0',
      's_locale': 'zh_CN',
      'statistics':
          '%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%226.72.0%22%2C%22abtest%22%3A%22%22%7D',
      'ts': '1659073412'
    };

    ///如果已登录，则加上access_Key字段
    if (isLogin == true) {
      String? _accessKey =
          SharedPreferenceUtil.getString(BilibiliSharedPreference.accessToken);
      final accessKeyEntry = <String, dynamic>{'access_key': _accessKey!};
      params.addEntries(accessKeyEntry.entries);
    }

    ///加上sign字段
    final signEntry = <String, dynamic>{'sign': ParamsSign.getSign(params)};
    params.addEntries(signEntry.entries);
    HYLoginRequest.getAccountMineData(params).then((value) {
      _userFace = value.data.face;

      ///将数据发送至我的界面
      accountMineEventBus.fire(value);
      setState(() {});
    });
  }
}
